package net.gyapp.markim.module.mine;

import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.easyder.wrapper.base.view.WrapperMvpFragment;
import com.easyder.wrapper.core.manager.ImageManager;
import com.easyder.wrapper.core.model.BaseVo;
import com.easyder.wrapper.core.scheduler.Task;
import com.easyder.wrapper.core.scheduler.TaskScheduler;
import com.gyf.barlibrary.ImmersionBar;

import net.gyapp.markim.ApiConfig;
import net.gyapp.markim.R;
import net.gyapp.markim.WrapperApplication;
import net.gyapp.markim.core.ImHelper;
import net.gyapp.markim.core.ImManager;
import net.gyapp.markim.module.basic.Helper;
import net.gyapp.markim.module.basic.base.CommonPresenter;
import net.gyapp.markim.module.basic.event.AccountChanged;
import net.gyapp.markim.module.basic.event.AccountIml;
import net.gyapp.markim.module.mine.account.BindMobileActivity;
import net.gyapp.markim.module.mine.account.ChangeMobileActivity;
import net.gyapp.markim.module.mine.account.CipherChangeActivity;
import net.gyapp.markim.module.mine.account.LoginActivity;
import net.gyapp.markim.module.mine.account.PersonalInfoActivity;
import net.gyapp.markim.module.mine.account.VCardActivity;
import net.gyapp.markim.module.mine.vo.MemberVo;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;


/**
 * Auther:  winds
 * Data:    2018/2/27
 * Version: 1.0
 * Desc:    我的
 */


public class MineFragment extends WrapperMvpFragment<CommonPresenter> {

    @BindView(R.id.iv_header)
    ImageView ivHeader;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.iv_grade)
    ImageView ivGrade;
    @BindView(R.id.tv_id)
    TextView tvId;
    @BindView(R.id.status_bar_view)
    View statusBarView;


    public static MineFragment newInstance() {
        return new MineFragment();
    }

    @Override
    public int getViewLayout() {
        return R.layout.fragment_mine;
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        ImmersionBar.with(this).init();
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        ImmersionBar.with(this).statusBarView(statusBarView).init();
        fillMemberInfo();
    }


    @Override
    protected void loadData(Bundle savedInstanceState) {

    }


    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
    }

    @Override
    public void showContentView(String url, BaseVo dataVo) {
        if (url.contains(ApiConfig.API_LOGOUT)) {
            processLogout();
        } else if (url.contains(ApiConfig.API_INFO)) {
            WrapperApplication.setMember((MemberVo) dataVo);
            fillMemberInfo();
        }
    }

    @Subscribe
    public void accountChanged(AccountChanged changed) {
        switch (changed.sign) {
            case AccountIml.ACCOUNT_NICK:
            case AccountIml.ACCOUNT_AVATAR:
                getInfo(true);
                break;
        }
    }

    @OnClick({R.id.iv_qr_code, R.id.layout_info, R.id.layout_bind_mobile, R.id.layout_change_mobile, R.id.layout_set_cipher, R.id.layout_logout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_qr_code:
                startActivity(VCardActivity.getIntent(_mActivity));
                break;
            case R.id.layout_info:
                startActivity(PersonalInfoActivity.getIntent(_mActivity));
                break;
            case R.id.layout_bind_mobile:
                if (WrapperApplication.isLogin() && TextUtils.isEmpty(WrapperApplication.getMember().userInfo.phone)) {
                    startActivity(BindMobileActivity.getIntent(_mActivity));
                } else {
                    showToast("手机号码已绑定");
                }
                break;
            case R.id.layout_change_mobile:
                if (WrapperApplication.isLogin() && !TextUtils.isEmpty(WrapperApplication.getMember().userInfo.phone)) {
                    startActivity(ChangeMobileActivity.getIntent(_mActivity));
                } else {
                    showToast("您未绑定手机号码");
                }
                break;
            case R.id.layout_set_cipher:
                startActivity(CipherChangeActivity.getIntent(_mActivity));
                break;
            case R.id.layout_logout:
                showConfirmDialog("确认退出帐号？");
                break;
        }
    }

    private void fillMemberInfo() {
        if (WrapperApplication.isLogin()) {
            MemberVo member = WrapperApplication.getMember();
            ImageManager.load(_mActivity, ivHeader, member.userInfo.userAvatar, R.drawable.placeholder_header);
            tvName.setText(TextUtils.isEmpty(member.userInfo.nick) ? member.userInfo.userName : member.userInfo.nick);
            tvId.setText(String.format("%1$s%2$s", "ID：", member.userInfo.userName));
        }
    }


    private void logout() {
        presenter.setNeedDialog(true);
        presenter.postData(ApiConfig.API_LOGOUT, BaseVo.class);
    }

    private void processLogout() {
        TaskScheduler.execute(new Task<Boolean>() {
            @Override
            public Boolean doInBackground() throws InterruptedException {
                ImManager.getInstance().logout(ImHelper.getSelf());
                WrapperApplication.setMember(null);
                Helper.setCipher(null);
                clearAlias();
                return true;
            }

            @Override
            public void onSuccess(Boolean result) {
                EventBus.getDefault().post(new AccountChanged(AccountIml.ACCOUNT_QUIT));
                startActivity(LoginActivity.getIntent(_mActivity, false, false));
                getActivity().finish();
            }
        });
    }

    private void getInfo(boolean show) {
        presenter.setNeedDialog(show);
        presenter.postData(ApiConfig.API_INFO, MemberVo.class);
    }

    private void showConfirmDialog(String message) {
        new AlertTipsDialog(_mActivity).setUp(new AlertTipsDialog.OnConfirmListener() {
            @Override
            public void onConfirm(Dialog dialog, View view) {
                dialog.dismiss();
                processLogout();
            }
        }, message, "退出", "取消").show();
    }

    private void clearAlias() {
        JPushInterface.deleteAlias(_mActivity, 0);
    }
}
